package com.xkstream.client.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.wuxiaolong.pullloadmorerecyclerview.PullLoadMoreRecyclerView;
import com.xkstream.client.R;
import com.xkstream.client.api.API;
import com.xkstream.client.application.Application;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.camera.CameraActivity;
import com.xkstream.client.camera.utils.FileUtils;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.entity.AnchorInfo;
import com.xkstream.client.entity.User;
import com.xkstream.client.entity.kt.BlogInfo;
import com.xkstream.client.entity.kt.BlogListData;
import com.xkstream.client.http.FileUploadUtil;
import com.xkstream.client.presenter.kt.MyZoneContract;
import com.xkstream.client.presenter.kt.MyZonePresenter;
import com.xkstream.client.rx.RxHelper;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.ui.adapter.MyZoneAdapter;
import com.xkstream.client.utils.AsyncImage;
import com.xkstream.client.utils.BitmapUtil;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.LeakUtil;
import com.xkstream.client.view.BottomPopupWindow;
import com.xkstream.client.view.CircleImageView;
import com.zego.zegoliveroom.ZegoLiveRoom;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.reactivestreams.Subscription;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by xiaoyi on 2017-9-27.
 * 我的空间
 */

public class MyZoneActivity extends BaseActivity<MyZoneContract.Presenter>
        implements MyZoneContract.View {
    @BindView(R.id.ivHeader)
    CircleImageView ivHeader;
    @BindView(R.id.refresh)
    PullLoadMoreRecyclerView refresh;

    @BindView(R.id.ivConver)
    ImageView ivConver;

    @BindString(R.string.delete_blog)
    String strDelete;
    List<BlogInfo> mDatas = new ArrayList<>();
    MyZoneAdapter adapter;

    private Uri coverPath;
    private String coverUrl;

    private Uri tmpPath;

    private static final int CODE_PHOTO = 0x1001;

    private static final int CODE_CONVER = 0X2001;

    private static final int CODE_CROP = 0X2003;

    private boolean loading;

    int page = 1;
    int pageSize = 10;
    MHandler mHandler;

    CompositeDisposable compositeDisposable;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_myzone);
        ButterKnife.bind(this);
        presenter = new MyZonePresenter(this);
        initRefreshView();

        reigsterRxbus();
        User user = Application.getUser();
        if (!TextUtils.isEmpty(user.getAnchor().getZone_img())) {
            AsyncImage.loadPhoto(this, user.getAnchor().getZone_img(), ivConver);
        }
        AsyncImage.loadPhoto(this, user.getExt_info().getHead_icon(), ivHeader);
    }

    private void initRefreshView() {
        adapter = new MyZoneAdapter(this, mDatas);
        refresh.setLinearLayout();
        refresh.setItemAnimator(new DefaultItemAnimator());
        refresh.setAdapter(adapter);
        refresh.getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 :
                                recyclerView.getChildAt(0).getTop();
                refresh.getSwipeRefreshLayout().setEnabled(topRowVerticalPosition > 0);
            }

        });
        adapter.setOnItemClickListener((v, pos) -> {
            if (v.getId() == R.id.tvAgree) {
                BlogInfo blog = mDatas.get(pos);
                blogUpvote(blog);
                v.setEnabled(false);
                compositeDisposable.add(Rxbus.getDefault().register(String.class)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe((integer -> {
                            int index;
                            try {
                                index = Integer.parseInt(integer);
                            } catch (Exception e) {
                                return;
                            }

                            if (index == 1) {
                                v.setEnabled(false);
                                blog.setUpvote_id(Application.getUser().getUser_code());
                                blog.setUpvote(blog.getUpvote() + 1);
                                mDatas.set(pos, blog);
                                adapter.notifyItemChanged(pos);
                            } else {
                                v.setEnabled(true);
                            }
                        })));

            } else if (v.getId() == R.id.tvDelete) {
                int realPos = refresh.getRecyclerView().getChildLayoutPosition(
                        (View) v.getParent().getParent().getParent()
                );
                showExitDialog(realPos);
            } else {
                Intent intent = new Intent(this, CommentDetailActivity.class);
                int realPos = refresh.getRecyclerView().getChildLayoutPosition(v);
                intent.putExtra("blog", mDatas.get(realPos));
                jumpToActivity(intent);
            }
        });

        refresh.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                if (!loading) {
                    page = 1;
                    loading = true;
                    compositeDisposable.add(Observable.timer(300, TimeUnit.MILLISECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe((delay) -> {
                                loading = false;
                                refresh.setPullLoadMoreCompleted();
                            }));
                    getBlogList(false);
                }
            }

            @Override
            public void onLoadMore() {
                if (!loading) {
                    page++;
                    loading = true;
                    getBlogList(false);
                    compositeDisposable.add(Observable.timer(300, TimeUnit.MILLISECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe((delay) -> {
                                        loading = false;
                                        refresh.setPullLoadMoreCompleted();
                                    }
                            ));
                }
            }
        });
        getBlogList(false);
    }


    private void reigsterRxbus() {
        compositeDisposable = new CompositeDisposable();
        compositeDisposable.add(Rxbus.getDefault().register(BlogInfo.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(blogInfo -> {
                    int pos = getChildPosition(blogInfo);
                    if (blogInfo.getDelete()) {
                        mDatas.remove(pos);
                        adapter.notifyItemRemoved(pos);
                    } else {
                        if (pos >= 0) {
                            mDatas.set(pos, blogInfo);
                            adapter.notifyItemChanged(pos);
                        }
                    }
                }));
        compositeDisposable.add(Rxbus.getDefault().register(String.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((str) -> {
                    if (str.equals("blog_refresh")) {
                        page = 1;
                        getBlogList(false);
                    }
                }));
    }

    private int getChildPosition(BlogInfo blog) {
        for (int i = 0; i < mDatas.size(); i++) {
            if (blog.getId().equals(mDatas.get(i).getId())) {
                return i;
            }
        }
        return -1;
    }

    @OnClick({R.id.ivBack, R.id.ivAdd, R.id.ivConver})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivAdd:
                showPhotoSelectedDialog(0);
                break;
            case R.id.ivConver:
                mHandler = new MHandler(this);
                showPhotoSelectedDialog(R.id.ivConver);
                break;
        }
    }


    private void showPhotoSelectedDialog(int id) {
        View view = View.inflate(this, R.layout.layout_choosephoto_dialog_zone, null);
        BottomPopupWindow popupWindow = new BottomPopupWindow(this, view);
        popupWindow.show(this);
        view.findViewById(R.id.tvCamera).setOnClickListener(
                (v) -> {
                    if (id == R.id.ivConver) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                        String path = FileUtils.getUploadPhotoFile(this);
                        File file = new File(path);
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        tmpPath = Uri.fromFile(file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpPath);
                        startActivityForResult(intent,
                                CODE_CONVER);
                    } else {
                        CameraActivity.lanuchForPhoto(this);
                    }
                    popupWindow.dismiss();

                }
        );
        view.findViewById(R.id.tvPhoto).setOnClickListener(
                (v) -> {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    if (id == R.id.ivConver) {
                        startActivityForResult(intent, CODE_CONVER);
                    } else {
                        startActivityForResult(intent, CODE_PHOTO);
                    }
                    popupWindow.dismiss();

                }
        );
        view.findViewById(R.id.tvCancel)
                .setOnClickListener((v) -> {
                    popupWindow.dismiss();
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_CONVER) {
            /*String path = getBitmapFromResult(data);
            ivConver.setTag("image");
            Bitmap bitmap = BitmapFactory.decodeFile(path);
            ivConver.setImageBitmap(bitmap);
            upLoadFile(path, ivConver);*/

            if (resultCode == RESULT_OK) {
                if (data != null && data.getData() != null) {
                    cropImage(data.getData(), CODE_CROP);
                } else if (tmpPath != null) {
                    cropImage(tmpPath, CODE_CROP);
                }
            }
        } else if (requestCode == CODE_CROP) {
            if (data != null && data.getExtras() != null) {
                Bitmap b = (Bitmap) data.getExtras().get("data");
                ivConver.setImageBitmap(b);
                upLoadFile(getBitmapFromResult(coverPath), ivHeader);
            } else if (coverPath != null) {
                String path = getBitmapFromResult(coverPath);
                Bitmap b = BitmapFactory.decodeFile(path);
                ivConver.setImageBitmap(b);
                upLoadFile(getBitmapFromResult(coverPath), ivHeader);
            }
        } else {
            if (resultCode == RESULT_OK) {
                String path = getBitmapFromResult(data);
                Intent intent = new Intent(this, SendTalkActivity.class);
                intent.putExtra("path", path);
                jumpToActivity(intent);
            } else {
                Intent intent = new Intent(this, SendTalkActivity.class);
                intent.putExtra("type", 0X1003);
                jumpToActivity(intent);
            }
        }
    }

    private String getBitmapFromResult(Intent data) {
        if (data != null) {

            String result = BitmapUtil.getPathByUri4kitkat(this,
                    data.getData() != null ? data.getData() :
                            Uri.parse(String.valueOf(data.getExtras().get("src_uri"))));
            return result;
        }
        return null;
    }

    private String getBitmapFromResult(Uri coverPath) {


        String result = BitmapUtil.getPathByUri4kitkat(this,
                coverPath);
        return result;


    }

    @Override
    public void showError(@NotNull String message) {
        showTopTips(message);
    }

    @Override
    public void showBlogList(@Nullable BaseData<BlogListData> data, boolean isDelete) {
        if (data.getCode() == 1) {
            if (page == 1) {
                if (isDelete) {
                    List<BlogInfo> list = data.getData().getList();
                    if (list != null && !list.isEmpty()
                            && list.size() >= 10) {
                        addLastItem(list.get(list.size() - 1));
                    }
                } else {
                    mDatas.clear();
                    mDatas.addAll(data.getData().getList());
                    adapter.notifyDataSetChanged();
                }
                refresh.setPushRefreshEnable(true);
            } else {
                if (isDelete) {
                    List<BlogInfo> list = data.getData().getList();
                    if (list != null && !list.isEmpty()
                            && list.size() >= 10) {
                        addLastItem(list.get(list.size() - 1));
                    }
                } else {
                    if (data.getData().getList() == null || data.getData().getList().isEmpty()) {
                        refresh.setPushRefreshEnable(false);
                    }
                    mDatas.addAll(data.getData().getList());
                    adapter.notifyItemInserted(adapter.getItemCount());
                }
            }
        } else {
            showTopTips(data.getMsg());
        }
    }

    private void addLastItem(BlogInfo info) {
        mDatas.add(info);
        adapter.notifyItemInserted(adapter.getItemCount());
    }


    @Override
    public void setPresenter(MyZoneContract.Presenter presenter) {
        this.presenter = presenter;
    }

    private void getBlogList(boolean isDelete) {
        Map<String, String> params = new HashMap<>();
        params.put("cur_page", String.valueOf(page));
        params.put("page_size", String.valueOf(pageSize));
        params.put("user_code", Application.getUser().getUser_code());
        presenter.getBlogList(params, isDelete);
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        refresh.setPullLoadMoreCompleted();
    }

    @Override
    public void showUpVoteResult(@NotNull BaseData<Object> t) {
        if (t.getCode() == 1) {
            showTopTips(R.string.upvote_success);
        } else {
            showTopTips(t.getMsg());
        }
        Rxbus.getDefault().post(String.valueOf(t.getCode()));
    }

    @Override
    public void showDeleteResult(@NotNull BaseData<Object> t, int index) {
        if (t.getCode() == 1) {
            mDatas.remove(index);
            adapter.notifyItemRemoved(index);
            showTopTips(R.string.delete_success);
            getBlogList(true);
        } else {
            showTopTips(t.getMsg());
        }
    }


    @Override
    public void showSetZoneBgResult(@NotNull BaseData<Object> t) {
        if (t.getCode() == 1) {
            showTopTips(R.string.upload_success);
            User user = Application.getUser();
            AnchorInfo info = user.getAnchor();
            info.setZone_img(coverUrl);
            user.setAnchor(info);
            Application.setUser(user);
        } else {
            showTopTips(t.getMsg());
        }
    }


    private static class MHandler extends Handler {
        WeakReference<MyZoneActivity> weakReference;

        public MHandler(MyZoneActivity activity) {
            this.weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            weakReference.get().tmpPath = null;
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
                    if (weakReference.get() != null) {
                        weakReference.get().hideLoading();
                        weakReference.get().setZoneBg(msg);
                    }
                    break;
                case FileUploadUtil.FAILED:
                    if (weakReference.get() != null) {
                        weakReference.get().hideLoading();
                        weakReference.get().showTopTips(R.string.upload_failed);
                    }
                    break;

            }

        }
    }

    private void setZoneBg(Message msg) {
        coverUrl = msg.getData().getString(FileUploadUtil.RESULT);
        Map<String, String> params = new HashMap<>();
        params.put("user_code", Application.getUser().getUser_code());
        params.put("zone_img", coverUrl);
        presenter.setZoneBg(params);
    }

    private void upLoadFile(String path, ImageView iv) {
        Map<String, String> textParams = new HashMap<>();
        textParams.put("bizImgPath", "show_h5");
        Map<String, String> params = new HashMap<>();
        params.put("iconFile", path);

        showLoading();
        new Thread(() -> {
            FileUploadUtil.uploadImageFile(API.FILEUPLOAD_HOST + API.UPLOAD_FILE,
                    textParams, params, mHandler, String.valueOf(iv.getTag()));
        }).start();

    }

    private void cropImage(Uri imageUri, int code) {
        Intent intent = new Intent("com.android.camera.action.CROP"); // 剪裁
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("scale", true);
        // 设置宽高比例
        intent.putExtra("aspectX", 2);
        intent.putExtra("aspectY", 1);
        // 设置裁剪图片宽高
        intent.putExtra("outputX", DeviceUtils.dp2px(this, 180));
        intent.putExtra("outputY", DeviceUtils.dp2px(this, 90));
        intent.putExtra("return-data", true);
        coverPath = Uri.fromFile(new File(FileUtils.getUploadPhotoFile(this)));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, coverPath);
        startActivityForResult(intent, code);
    }


    private void blogUpvote(BlogInfo blog) {
        Map<String, String> params = new HashMap<>();
        params.put("blog_id", blog.getId());
        params.put("user_code", Application.getUser().getUser_code());
//        params.put("upvote_id")
        params.put("is_like", "1");
        presenter.blogUpVote(params);
    }

    private void deleteBlog(int index) {
        BlogInfo blogInfo = mDatas.get(index);
        Map<String, String> params = new HashMap<>();
        params.put("user_code", Application.getUser().getUser_code());
        params.put("id", blogInfo.getId());
        presenter.deleteBlog(params, index);
    }

    private void showExitDialog(int index) {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle(strDelete);
        dialog.setListener(() -> {
            deleteBlog(index);
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LeakUtil.fixInputMethodManagerLeak(this);
        compositeDisposable.clear();
    }
}
